'use strict';

//方法同步执行
var Sync = function(){
	this._Queue = {};
};
Sync.prototype = {
	// 创建排队
	createQueue: function(key, asyncFun, args){
		if(!this._Queue.hasOwnProperty(key)){
			this._Queue[key] = [];
		}
		this._Queue[key].push({
			Fun: asyncFun,
			Args: args
		});

		if(this._Queue[key].length == 1){
			this.exec(asyncFun, args);
		}
	},
	// 执行排队
    exec: function(asyncFun, args){
        asyncFun.apply(null, args);
    },
    // 删除第一个排队并执行下一个排队
    deleteQueue: function(key){
    	if(this._Queue.hasOwnProperty(key)){
    		this._Queue[key].shift();

    		if(this._Queue[key].length > 0){
    			this.exec(this._Queue[key][0].Fun, this._Queue[key][0].Args);
    		}
    		else{
    			delete this._Queue[key];
    		}
    	}
	},
	// 执行中
	getExecuting: function(key){
		if(this._Queue.hasOwnProperty(key)){
			return this._Queue[key][0];
		}
		else{
			return null;
		}
	},
	// 等待中
	getWaiting: function(key){
		if(this._Queue.hasOwnProperty(key) && this._Queue[key].length > 1){
			var arrWaiting = [];
			for(var i=1; i<this._Queue[key].length; i++){
				arrWaiting.push(this._Queue[key][i]);
			}
			return arrWaiting;
		}
		else{
			return null;
		}
	},
	// 排队中
	getQueue: function(key){
		return this._Queue[key];
	}
};

var _Sync = new Sync();

exports.lock = function(key, asyncFun, args){
	_Sync.createQueue(key, asyncFun, args);
};

exports.unLock = function(key){
	_Sync.deleteQueue(key);
};

exports.IsExist = function(key){
	var queueTasks = _Sync.getQueue(key);
	if(queueTasks && queueTasks.length > 0){
		return true;
	}
	else{
		return false;
	}
};
